package com.atguigu.ucenter.member.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.ucenter.member.config.WxConfig;
import com.atguigu.ucenter.member.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * 微信扫码回调API
 * @author zy
 */
@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
@Api(value = "WxApiController", description = "微信登录接口8150")
public class WxApiController {

    @ApiOperation("生成登录二维码,返回校验码")
    @GetMapping("login")
    public String login() throws UnsupportedEncodingException {
        //需要进行编码
        String redirectUri = URLEncoder.encode(WxConfig.REDIRECT_URL, "UTF-8");

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=edu";
        String url = String.format(baseUrl, WxConfig.APPID, redirectUri);
        return "redirect:" + url;
    }

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private MemberService memberService;

    @ApiOperation("扫码后并确认的回调,获取code和[state/验证码和传过来的state]")
    @GetMapping("/callback")
    public String callBack(String code, String state) {
        //  请求授权码 和openid
        String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String url = String.format(baseUrl, WxConfig.APPID, WxConfig.APPSECRET, code);
        String data = restTemplate.getForObject(url, String.class);

        //返回授权码和 openId
        HashMap<String, String> map1 = JSON.parseObject(data, new TypeReference<HashMap<String, String>>() {
        });
        String accessToken = map1.get("access_token");
        String openid = map1.get("openid");
        //根据授权码和 openId获取用户信息
        String infoBaseUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=%s" +
                "&openid=%s";
        String infoUrl = String.format(infoBaseUrl, accessToken, openid);
        String info = restTemplate.getForObject(infoUrl, String.class);
        HashMap<String, String> userInfo = JSON.parseObject(info, new TypeReference<HashMap<String, String>>() {
        });
        String token = memberService.wxLogin(userInfo);
        //返回JWTtoken令牌
        return "redirect:http://localhost:3000?token=" + token;

    }

}
